/*
NAME: 
DESCRIPTION: 描述;
PARAMETER:
	[
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'}
		},
		{
			name : 'auto_save',
			title : '自动保存',
			type : 'RadioBox',
			property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
		}
	]
	
 VERSION_HISTORY:
	V1.00 2021-03-08 Scott Sun
		1.新版本
		
 HELP:
	  <html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 标题 </ p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/

// 引入模块 包 外部参数
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm ? $.ikm : require('topcam.ikm6')($);
var GEN = $.gen;
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db;
var PAR = {};
if ($.par) { PAR = $.par } else if ($.hasOwnProperty('script_parameter')) { PAR = JSON.parse($.script_parameter); }
if (mode === "aimdfm") {
	IKM.crud("updateRow", {
        table: "pdm_aimdfm_task", 
        data: { current_process_title: $.process_title }, 
        where: { id: $.task_id }
    })
}
var Status = 'ok';
var resultData = [];
var par = PAR;  // 接收参数
var default_par = { // 设置默认参数
	step: "orig",
	auto_save: "No",
	units: "mm"
}
for (var key in default_par) {
	if (!par.hasOwnProperty(key) || par[key] == "") {
		par[key] = default_par[key]
	}
}

// 定义变量
var job = Job;

try {
	// 常规验证 准备工作
	
	if (!GEN.isJobExists({ job: job })) { throw "料号" + job + "不存在" }
	if (!GEN.isJobOpen({ job: job })) { GEN.openJob({ job: job }) }
	if (mode == "aimdfm") {
		if (GEN.checkInout({job: job,mode: "test"}) != 0) {
			throw "the job check"
		}
		GEN.checkInout({job: job,mode: "out"});
	}

	// 主体
	var stepList = GEN.getStepList({job:job})     // 工作step列表
	stepList = stepList.filter(function(step){
		var reg = new RegExp(par.step,"ig");
		return reg.test(step);
	})

	IKM.msg(
		getLayer() // 获取所有层
	)
	IKM.msg(
		getLayer({context:"board"}) // 获取board层
	)
	IKM.msg(
		getLayer({context:"board", layer_type:"signal"}) // 获取signal board层
	)
	IKM.msg(
		getLayer({context:"board", layer_type:"signal", side: /top|bot/}) // 获取外层
	)
	IKM.msg(
		getLayer({name:/\+\+\+$/}) // 获取后缀为+++的层
	)
	IKM.msg(
		getLayer({name:function(v){return v.length > 10}}) // 获取字符长度大于10 的层
	)
	
	// 保存料号
	if (/yes/ig.test(par.auto_save)) { 
		GEN.checkInout({ job: job, mode: "out" }); 
		GEN.saveJob({ job: job }); 
		GEN.checkInout({ job: job, mode: "in" });
	} 
	
	// 结尾返回 固定写法
	var Return = "Done"
	if (mode === "aimdfm") {
		IKM.crud("updateRow", {
            table: "pdm_aimdfm_task", 
            data: { progress: 100 }, 
            where: { id: $.task_id }
        })
		var tmperr = { type: "info", title: "操作完成, 请注意检查!" }
		if (GEN.hasError()) {
			Status = 'error'; 
			tmperr = { type: "error", title: "GEN错误!", detail: [{ desc: GEN.STATUS.join("\n") }] }
		}
		resultData.push(tmperr);
		Return = { status: Status, result_data: resultData };
	}
	return Return
} catch (e) {
	if(GEN.STATUS.length > 0) {
		IKM.msg(GEN.STATUS.join("\n")); 
	}
	IKM.msg(e);
	Status = 'error';
	resultData.push({ type: "error", title: "脚本执行出错!", detail: [{ desc: _.toString(e) }] });
	return (mode === "aimdfm") ? { status: Status, result_data: resultData } : "Error";
}

/**
 * 获取层别
 * @param {Object} 过滤选项
 * @returns {Array}
 */
 function getLayer(props) {
	if (!props) {
		props = {};
	}
	var matrix = GEN.getMatrix({ job: job });
	return Object.keys(matrix).reduce(function (a, b) {
		var info = matrix[b];
		var ret = true;
		for (var _key in props) {
			if (info[_key]) {
				if (/object string|object number/ig.test({}.toString.call(props[_key]))) {
					if (props[_key] != info[_key]) {
						ret = false;
					}
				}
				if (/object RegExp/ig.test({}.toString.call(props[_key]))) {
					if (!props[_key].test(info[_key])) {
						ret = false;
					}
				}
				if (/object function/ig.test({}.toString.call(props[_key]))) {
					if (!props[_key](info[_key])) {
						ret = false;
					}
				}
			}
		}
		if (ret) {
			a.push(props.res == "info" ? info : b);
		}
		return a;
	}, []);
}